﻿const express = require('express'); 
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const axios = require('axios');
const { finished } = require('stream');
const { promisify } = require('util');
const app = express();
const port = 3000;
const archiver = require('archiver');
const baseFolderPath = path.join(__dirname, 'templates');
app.use(cors());
app.use(bodyParser.json());

// SQLite 连接配置
const db = new sqlite3.Database('./devstar.db', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    console.error('Error opening database:', err.message);
  } else {
    console.log('Connected to SQLite database');
  }
});
app.get('/api/plugin-data', async (req, res) => {
  try {
    // 获取所有标签
    db.all('SELECT id, name FROM plugin_tags', [], (err, tags) => {
      if (err) {
        console.error('Failed to fetch tags:', err);
        return res.status(500).send('Error fetching tags');
      }

      // 获取所有插件及其对应的标签
      db.all(`
        SELECT p.id AS plugin_id, p.name AS plugin_name, t.id AS tag_id, t.name AS tag_name 
        FROM plugins p
        JOIN plugin_tag_map ptm ON p.id = ptm.plugin_id
        JOIN plugin_tags t ON ptm.tag_id = t.id
      `, [], (err, pluginsWithTags) => {
        if (err) {
          console.error('Failed to fetch plugin data:', err);
          return res.status(500).send('Error fetching plugin data');
        }

        // 按标签分组插件
        const groupedData = tags.map(tag => ({
          label: tag.name,
          children: pluginsWithTags
            .filter(pl => pl.tag_id === tag.id)
            .map(pl => ({ label: pl.plugin_name }))
        }));

        // 返回分组数据
        res.json(groupedData);
      });
    });
  } catch (error) {
    console.error('Failed to fetch plugin data:', error);
    res.status(500).send('Error fetching plugin data');
  }
});

app.get('/api/software-data', async (req, res) => {
  try {
    // 获取所有标签
    db.all('SELECT id, name FROM software_tags', [], (err, tags) => {
      if (err) {
        console.error('Failed to fetch tags:', err);
        return res.status(500).send('Error fetching tags');
      }

      // 获取所有软件包及其对应的标签
      db.all(`
        SELECT sp.id AS software_id, sp.name AS software_name, t.id AS tag_id, t.name AS tag_name 
        FROM software_packages sp
        JOIN software_tag_map stm ON sp.id = stm.software_id
        JOIN software_tags t ON stm.tag_id = t.id
      `, [], (err, softwareWithTags) => {
        if (err) {
          console.error('Failed to fetch software data:', err);
          return res.status(500).send('Error fetching software data');
        }

        // 按标签分组软件包
        const groupedData = tags.map(tag => ({
          label: tag.name,
          children: softwareWithTags
            .filter(sw => sw.tag_id === tag.id)
            .map(sw => ({ label: sw.software_name }))
        }));

        // 返回分组数据
        res.json(groupedData);
      });
    });
  } catch (error) {
    console.error('Failed to fetch software data:', error);
    res.status(500).send('Error fetching software data');
  }
});

app.get('/api/environment', async (req, res) => {
  const { name } = req.query;
  console.log('Starting query for environment:', name);
  try {
    // 使用 SQLite 的查询语法
    db.get('SELECT selectedSoftwares, selectedPlugins FROM environments WHERE name = ?', [name], (err, results) => {
      if (err) {
        console.error('Error during database query:', err);
        return res.status(500).json({ message: 'Internal server error' });
      }

      if (results) {
        const { selectedSoftwares, selectedPlugins } = results;
        res.json({
          Softwares: parseData(selectedSoftwares),
          Plugins: parseData(selectedPlugins),
        });
      } else {
        res.status(404).json({ message: 'Environment not found' });
      }
    });
  } catch (error) {
    console.error('Error during database query:', error);
    res.status(500).json({ message: 'Internal server error' });
  }
});

// 解析数据，如果是 JSON 格式则解析，否则按逗号分隔
function parseData(data) {
  if (!data) return [];
  
  // 尝试解析 JSON 格式的数据
  try {
    return JSON.parse(data);
  } catch (e) {
    console.log('Data is not in JSON format, treating as comma-separated string');
    // 如果不是 JSON 格式，将其视为逗号分隔的字符串
    return data.split(',');
  }
}

app.get('/api/ide-data', async (req, res) => {
  try {
    db.all('SELECT id, name, description FROM ide_table', [], (err, results) => {
      if (err) {
        res.status(500).json({ error: err.message });
      } else {
        res.json(results);
      }
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

app.get('/api/my-ide-data', async (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1];  // 获取请求头中的 token

  if (!token) {
    return res.status(401).json({ error: 'Token is required' });
  }

  try {
    // 验证 token 并获取用户名
    const { username } = await verifyToken(token);

    // 使用从第三方获取的用户名进行数据库查询
    db.all('SELECT id, name, description FROM ide_templates WHERE author = ?', [username], (err, results) => {
      if (err) {
        res.status(500).json({ error: err.message });
      } else {
        res.json(results);
      }
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});


app.get('/api/my-ide-data', async (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1];  // 获取请求头中的 token

  if (!token) {
    return res.status(401).json({ error: 'Token is required' });
  }

  try {
    // 验证 token 并获取用户名
    const { username } = await verifyToken(token);

    // 使用从第三方获取的用户名进行数据库查询
    db.all('SELECT id, name, description FROM ide_templates WHERE author = ?', [username], (err, results) => {
      if (err) {
        res.status(500).json({ error: err.message });
      } else {
        res.json(results);
      }
    });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});


app.post('/api/create-template', async (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1];
  console.log(token);
  if (!token) {
    return res.status(401).json({ error: 'Token is required' });
  }
  const { ideName, ideDescription, softwares, plugins } = req.body;
  const { username } = await verifyToken(token);
  console.log(username);
  try {
    const folderPath = path.join(__dirname, 'templates', username);
    const filePath = path.join(folderPath, ideName);

    // 创建作者文件夹（如果不存在）
    if (!fs.existsSync(folderPath)) {
      fs.mkdirSync(folderPath, { recursive: true });
    }

    console.log(softwares);
    // 创建空文件
    const tags = '';

    // 插入数据到SQLite数据库
    const query = `
      INSERT INTO ide_templates (name, description, author, software, vscode_plugins, tags, path)
      VALUES (?, ?, ?, ?, ?, ?, ?)
    `;
    const values = [ideName, ideDescription, username, softwares.join(','), plugins.join(','), tags, filePath];

    // 使用Promise封装SQLite的查询操作
    const insertTemplate = (query, values) => new Promise((resolve, reject) => {
      db.run(query, values, function(err) {
        if (err) {
          return reject(err);
        }
        resolve(this.lastID); // 返回插入的ID
      });
    });

    const result = await insertTemplate(query, values);
    console.log(filePath);
    
    if (!fs.existsSync(filePath)) {
      fs.mkdirSync(filePath, { recursive: true });
    }

    // 创建 Dockerfile
    if (true) {
      const devcontainerPath = path.join(filePath, '.devcontainer');
      if (!fs.existsSync(devcontainerPath)) {
        fs.mkdirSync(devcontainerPath, { recursive: true });
      }

      // 从数据库获取软件包和插件
      const getSoftwaresQuery = 'SELECT software FROM ide_templates WHERE name = ?';
      const getPluginsQuery = 'SELECT vscode_plugins FROM ide_templates WHERE name = ?';

      const getValues = (query, param) => new Promise((resolve, reject) => {
        db.all(query, [param], (err, rows) => {
          if (err) reject(err);
          resolve(rows);
        });
      });

      const [software_rows] = await getValues(getSoftwaresQuery, ideName);
      const softwares = software_rows.length > 0 ? software_rows[0].software.split(',').map(item => item.trim()) : [];

      const [plugin_rows] = await getValues(getPluginsQuery, ideName);
      console.log(plugin_rows);
      const plugins = plugin_rows.length > 0 ? plugin_rows[0].vscode_plugins.split(',').map(item => item.trim()) : [];

      console.log(softwares);
      console.log(plugins);
      const finishedAsync = promisify(finished);
      const dockerfilePath = path.join(devcontainerPath, 'dockerfile');
      const fileStream = fs.createWriteStream(dockerfilePath);

      fileStream.write('FROM mcr.microsoft.com/devcontainers/base:ubuntu-20.04\n');
      fileStream.write('ENV DEBIAN_FRONTEND=noninteractive\n');
      fileStream.write('RUN apt-get update && \\\n');
      fileStream.write('apt-get install -y software-properties-common curl wget git &&  \\\n');
      fileStream.write('apt-get clean\n');

      // 使用 Promise.all 确保所有的异步操作完成后再结束文件流
      const softwarePromises = softwares.map(async (word) => {
        const [rows] = await getValues('SELECT code FROM software_packages WHERE name = ?', word);
        const code = rows.length > 0 ? rows[0].code : null;
        if (code != null) fileStream.write(code + '\n');
        console.log(code);
      });

      await Promise.all(softwarePromises);

      // 添加额外的 Dockerfile 内容
      fileStream.write('WORKDIR /workspace\n');

      // 确保文件流正确结束
      fileStream.end();

      // 等待文件流完成
      await finishedAsync(fileStream);
    }

    // 创建 devcontainer.json
    if (true) {
      const devcontainerPath = path.join(filePath, '.devcontainer');
      if (!fs.existsSync(devcontainerPath)) {
        fs.mkdirSync(devcontainerPath, { recursive: true });
      }

      const devcontainerJsonPath = path.join(devcontainerPath, 'devcontainer.json');
      let extensions = [];

      async function getPluginIDs(plugins) {
        const promises = plugins.map(async function(word) {
          console.log(word);
          const [rows] = await getValues('SELECT pluginID FROM plugins WHERE name = ?', word);
          const code = rows.length > 0 ? rows[0].pluginID : null;
          console.log(code);
          if (code != null) extensions.push(code);
        });

        // 等待所有异步操作完成
        await Promise.all(promises);

        // 返回填充后的 extensions 数组
        return extensions;
      }

      getPluginIDs(plugins).then(result => {
        console.log('Final extensions array:', result);
        const devcontainerJsonContent = {
          name: ideName,
          build: {
            dockerfile: "dockerfile",
            context: "."
          },
          extensions: result,
          settings: {
            "python.pythonPath": "/usr/bin/python"
          },
          postCreateCommand: "pip install -r requirements.txt",
          forwardPorts: [8000]
        };
        console.log(devcontainerJsonContent);
        fs.writeFileSync(devcontainerJsonPath, JSON.stringify(devcontainerJsonContent, null, 4), 'utf8');
      });
    }

    res.status(201).json({ message: 'Template created successfully', templateId: result });
  } catch (error) {
    console.error('Error creating template:', error);
    res.status(500).json({ error: 'Failed to create template' });
  }
});
app.post('/api/delete-template', async (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1];
  console.log(token);
  if (!token) {
    return res.status(401).json({ error: 'Token is required' });
  }
  const { ideName } = req.body;
  console.log(req.body);
  console.log(ideName);
  const { username } = await verifyToken(token);
  if (!ideName) {
      return res.status(400).json({ error: 'Template name is required' });
  }

  // 根据模板名生成目录路径
  const folderPath = path.join(__dirname, 'templates', username, ideName);

  // 检查目录是否存在并删除
  fs.access(folderPath, fs.constants.F_OK, async (err) => {
      if (err) {
          console.error(`Directory not found: ${folderPath}`);
          return res.status(404).json({ error: 'Directory not found' });
      }

      // 使用 fs.rm 删除目录及其内容
      fs.rm(folderPath, { recursive: true, force: true }, async (err) => {
          if (err) {
              console.error(`Error deleting directory: ${folderPath}`, err);
              return res.status(500).json({ error: 'Failed to delete directory' });
          }

          try {
              // 删除数据库中相应行的数据
              const deleteTemplateQuery = 'DELETE FROM ide_templates WHERE name = ? AND author = ?';
              const deleteValues = [ideName, username];
              
              // 使用 Promise 封装 SQLite 的删除操作
              const deleteTemplate = (query, values) => new Promise((resolve, reject) => {
                  db.run(query, values, function(err) {
                      if (err) {
                          return reject(err);
                      }
                      resolve(this.changes); // 获取删除影响的行数
                  });
              });

              const changes = await deleteTemplate(deleteTemplateQuery, deleteValues);

              if (changes === 0) {
                  return res.status(404).json({ error: 'No record found in the database' });
              }
              res.json({ message: `Directory ${ideName} and corresponding database record successfully deleted` });
          } catch (dbErr) {
              console.error('Database error:', dbErr);
              return res.status(500).json({ error: 'Failed to delete database record' });
          }
      });
  });
});
app.post('/api/generate-file', async (req, res) => {
  console.log(req.body.params);
  const { name, description } = req.body.params;

  // 查询软件列表
  const softwareQuery = 'SELECT software FROM ide_templates WHERE name = ?';
  const pluginsQuery = 'SELECT vscode_plugins FROM ide_templates WHERE name = ?';

  const softwares = await new Promise((resolve, reject) => {
    db.get(softwareQuery, [name], (err, row) => {
      if (err) return reject(err);
      const softwareList = row && row.software ? row.software.split(',').map(item => item.trim()) : [];
      resolve(softwareList);
    });
  });

  const plugins = await new Promise((resolve, reject) => {
    db.get(pluginsQuery, [name], (err, row) => {
      if (err) return reject(err);
      const pluginList = row && row.vscode_plugins ? row.vscode_plugins.split(',').map(item => item.trim()) : [];
      resolve(pluginList);
    });
  });

  console.log(softwares);
  console.log(plugins);

  const filePath = path.join(__dirname, 'DockerFile');
  const fileStream = fs.createWriteStream(filePath);
  
  fileStream.write('FROM mcr.microsoft.com/devcontainers/base:ubuntu-20.04\n');
  fileStream.write('ENV DEBIAN_FRONTEND=noninteractive\n');
  fileStream.write('RUN apt-get update && \\\n');
  fileStream.write('apt-get install -y software-properties-common curl wget git &&  \\\n');
  fileStream.write('apt-get clean\n');

  // 使用 Promise.all 确保所有的异步操作完成后再结束文件流
  const softwarePromises = softwares.map(async (word) => {
    const softwareQuery = 'SELECT code FROM software_packages WHERE name = ?';
    const code = await new Promise((resolve, reject) => {
      db.get(softwareQuery, [word], (err, row) => {
        if (err) return reject(err);
        resolve(row ? row.code : null);
      });
    });
    if (code) fileStream.write(code + '\n');
  });

  const pluginPromises = plugins.map(async (word) => {
    const pluginQuery = 'SELECT pluginID FROM plugins WHERE name = ?';
    const code = await new Promise((resolve, reject) => {
      db.get(pluginQuery, [word], (err, row) => {
        if (err) return reject(err);
        resolve(row ? row.pluginID : null);
      });
    });
    if (code) fileStream.write('RUN code-server --install-extension ' + code + '\n');
  });

  await Promise.all([...softwarePromises, ...pluginPromises]);

  fileStream.write('WORKDIR /workspace\n');
  fileStream.write('CMD ["code", "--user-data-dir", "/root/.config/Code", "--no-sandbox", "/workspace"]\n');
  
  fileStream.end(() => {
    const archivePath = path.join(__dirname, 'output.zip');
    const archiveStream = fs.createWriteStream(archivePath);

    const archiverInstance = archiver('zip', {
      zlib: { level: 1 } // 设置压缩级别
    });

    archiverInstance.pipe(archiveStream);
    archiverInstance.file(filePath, { name: 'DockerFile' });
    archiverInstance.file('./VSCodeUserSetup-x64-1.91.0.exe', { name: 'VSCodeUserSetup-x64-1.91.0.exe' });
    archiverInstance.finalize();

    archiveStream.on('close', () => {
      res.download(archivePath, 'output.zip', err => {
        if (err) {
          console.log(err);
        }
        fs.unlinkSync(filePath);
        fs.unlinkSync(archivePath);
      });
    });
  });
});
app.post('/api/generate-file2', async (req, res) => {
  const { name, description } = req.body.params;

  // 查询软件列表
  const softwareQuery = 'SELECT software FROM ide_templates WHERE name = ?';
  const pluginsQuery = 'SELECT vscode_plugins FROM ide_templates WHERE name = ?';

  const softwares = await new Promise((resolve, reject) => {
    db.get(softwareQuery, [name], (err, row) => {
      if (err) return reject(err);
      const softwareList = row && row.software ? row.software.split(',').map(item => item.trim()) : [];
      resolve(softwareList);
    });
  });

  const plugins = await new Promise((resolve, reject) => {
    db.get(pluginsQuery, [name], (err, row) => {
      if (err) return reject(err);
      const pluginList = row && row.vscode_plugins ? row.vscode_plugins.split(',').map(item => item.trim()) : [];
      resolve(pluginList);
    });
  });

  console.log(softwares);
  console.log(plugins);

  const filePath = path.join(__dirname, 'DockerFile');
  const fileStream = fs.createWriteStream(filePath);
  
  fileStream.write('FROM mcr.microsoft.com/devcontainers/base:ubuntu-20.04\n');
  fileStream.write('ENV DEBIAN_FRONTEND=noninteractive\n');
  fileStream.write('RUN apt-get update && \\\n');
  fileStream.write('apt-get install -y software-properties-common curl wget git &&  \\\n');
  fileStream.write('apt-get clean\n');

  // 使用 Promise.all 确保所有的异步操作完成后再结束文件流
  const softwarePromises = softwares.map(async (word) => {
    const softwareQuery = 'SELECT code FROM software_packages WHERE name = ?';
    const code = await new Promise((resolve, reject) => {
      db.get(softwareQuery, [word], (err, row) => {
        if (err) return reject(err);
        resolve(row ? row.code : null);
      });
    });
    if (code) fileStream.write(code + '\n');
  });

  const pluginPromises = plugins.map(async (word) => {
    const pluginQuery = 'SELECT pluginID FROM plugins WHERE name = ?';
    const code = await new Promise((resolve, reject) => {
      db.get(pluginQuery, [word], (err, row) => {
        if (err) return reject(err);
        resolve(row ? row.pluginID : null);
      });
    });
    if (code) fileStream.write('RUN code-server --install-extension ' + code + '\n');
  });

  await Promise.all([...softwarePromises, ...pluginPromises]);

  fileStream.write('WORKDIR /workspace\n');
  
  fileStream.end(() => {
    res.download(filePath, 'DockerFile', err => {
      if (err) {
        console.log(err);
      }
      //fs.unlinkSync(filePath); // Uncomment this if you want to delete the file after download
    });
  });
});

app.get('/api/download',async (req, res) => {
    const token = req.headers['authorization']?.split(' ')[1];
    console.log(token);

    if (!token) {
      return res.status(401).json({ error: 'Token is required' });
    }
    const { name } = req.query;
    const { username } = await verifyToken(token);
    // 设置文件路径
    const originalFilePath = path.join("./", "1.ps1");
    const newFilePath = path.join("./", `${name}.ps1`);

    // 读取原始文件
    fs.readFile(originalFilePath, 'utf8', (err, data) => {
        if (err) {
            console.error(`Error reading file: ${originalFilePath}`, err);
            return res.status(500).json({ error: 'Failed to read the file' });
        }

        // 在文件首行添加内容
        const newContent = `$folderName = "${username}/${name}"\n${data}`;

        // 将新内容写入到新文件
        fs.writeFile(newFilePath, newContent, 'utf8', (err) => {
            if (err) {
                console.error(`Error writing file: ${newFilePath}`, err);
                return res.status(500).json({ error: 'Failed to write the file' });
            }

            // 发送新文件
            res.download(newFilePath, `${name}.ps1`, (err) => {
                if (err) {
                    console.error(`Error downloading file: ${newFilePath}`, err);
                    return res.status(500).json({ error: 'Failed to download file' });
                }

                // 删除生成的文件
                fs.unlink(newFilePath, (err) => {
                    if (err) {
                        console.error(`Error deleting file: ${newFilePath}`, err);
                    } else {
                        console.log(`File deleted: ${newFilePath}`);
                    }
                });
            });
        });
    });
});


app.get('/download-devcontainer/:folderName', (req, res) => {
  const folderName = req.params.folderName;
  console.log(folderName);
  const devcontainerPath = path.join(baseFolderPath, folderName, '.devcontainer');
  console.log(devcontainerPath);
  // 确保 .devcontainer 文件夹存在
  if (!fs.existsSync(devcontainerPath)) {
      return res.status(404).send('The requested .devcontainer folder does not exist.');
  }

  // 创建一个压缩流
  const archive = archiver('zip', { zlib: { level: 9 } });

  // 设置响应头以下载ZIP文件
  res.attachment(`${folderName}-devcontainer.zip`);

  // 处理错误事件
  archive.on('error', (err) => {
      res.status(500).send({ error: err.message });
  });

  // 将压缩流写入响应
  archive.pipe(res);

  // 将 .devcontainer 文件夹添加到压缩流中
  archive.directory(devcontainerPath, false);
  archive.finalize();
});

app.get('/api/downloadInstaller', (req, res) => {
  const filePath = path.join(__dirname, '../installer', 'DevStar IDE Desktop.exe');

  // 检查文件是否存在
  if (fs.existsSync(filePath)) {
      res.download(filePath, 'DevStar IDE Desktop.exe', (err) => {
          if (err) {
              console.error("下载出错:", err);
              res.status(500).send("服务器错误");
          }
      });
  } else {
      res.status(404).send('文件未找到');
  }
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

app.post('/api/login', async (req, res) => {
  const { username, password } = req.body; // 从请求体中获取用户名和密码
  const url = `https://devstar.cn/api/v1/users/${username}/tokens`;
  // Base64编码用户名和密码（使用 Buffer）
  const base64Credentials = Buffer.from(`${username}:${password}`).toString('base64');

  const tokenName = generateTokenName(10); // 生成一个随机的 token 名称
  const postData = {
      "name": tokenName
  };

  try {
      // 发送POST请求到外部API，附带授权信息和请求体
      const response = await axios.post(url, postData, {
          headers: {
              'Content-Type': 'application/json',
              'Authorization': `Basic ${base64Credentials}`
          }
      });

      // 登录成功，返回外部API的响应数据
      res.json(response.data);
  } catch (error) {
      console.error('登录失败:', error.response ? error.response.data : error.message);
      res.status(500).json({ error: '登录失败' });
  }
});

// 生成随机 Token 名称的函数
function generateTokenName(length) {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

app.post('/api/logout', async (req, res) => {
  const { username, token } = req.body;
  const url = `https://devstar.cn/api/v1/users/${username}/tokens/${token}`;

  try {
    const response = await axios.delete(url, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    });
    res.json(response.data); // 成功时返回登出数据
  } catch (error) {
    console.error('登出失败:', error.response ? error.response.data : error.message);
    res.status(500).json({ error: '登出失败' });
  }
});

async function verifyToken(token) {
  if (!token) {
    throw new Error('Token is required');
  }

  try {
    // 调用外部API验证token
    const response = await axios.get('https://devstar.cn/api/devcontainer/user', {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `token ${token}`
      }
    });
    console.log(response);
    // 返回API响应的数据
    return {
      status: response.status,
      username: response.data.data.username
    };
  } catch (error) {
    throw new Error('Error verifying token: ' + error.message);
  }
}
app.get('/api/ping', (req, res) => {
  res.status(200).json({ message: 'pong' });
});

app.post('/api/verify-token', async (req, res) => {

  const token = req.body.token;  // 从请求的body中获取token

  if (!token) {
      return res.status(400).json({ error: 'Token is required' });
  }

  try {
      // 调用外部API验证token
      const response = await axios.get('https://devstar.cn/api/devcontainer/user', {
          headers: {
              'Content-Type': 'application/json',
              'Authorization': `token ${token}`
          }
      });
      
      // 如果响应成功，返回响应的状态码
      res.status(200).json({ status: response.status, message: 'Token is valid' , username: response.data.data.username});
  } catch (error) {
      // 如果发生错误，返回错误信息
      res.status(500).json({ error: 'Error verifying token', details: error.message });
  }
});